/**
 * Created by YiFeng on 2016/10/5.
 */

;!(function(){
	var __functionForDataModel=function(Ladder){
        var username=DataModelConfig.username||Ladder.getRequestParam("loginuser")||Ladder.getStore("loginuser");
        if(!username){
            window.parent.window.location.href = YFLib.Service.parseUrl(URLS.URL_Login)+"?redirect="+encodeURIComponent(window.location.href);
        }
        //初始化设置
        $(function () {
            var conn = $("#connname").val(DataModelConfig.servername);
            var table = $("#table").val(DataModelConfig.servertable);
        })
        var tempData = {};
        Ladder.layout();
        var lefttab=new Ladder.InTab("#leftintab",{container:"#leftintab"});
        lefttab.addTab({
            id: "templateview",
            title: "数据模版列表",
            target: "#grid",
            current: true
        });
        if(/(,|^)tables(,|($))/.test(DataModelConfig.fitview)){
            lefttab.addTab({
                title: "数据库表",
                target: "#databasegird",
                onFirst: function() {
                    databasegrid.loadRemote();
                }
            });
        }
        if(/(,|^)back(,|($))/.test(DataModelConfig.fitview)){
            lefttab.addTab({
                title: "备份历史",
                target: "#backhistory",
                onFirst: function() {
                    backgrid.loadRemote();
                },
                onClick: function() {
                    var name = $("#name").val();
                    if(name) {
                        backgrid.setCondition({
                            forms: null,
                            pager: null,
                        });
                        // backgrid.loadRemote();
                        backgrid.setConditionForm("name:like", name, true);
                    }
                }
            });
        }
        if(/(,|^)tools(,|($))/.test(DataModelConfig.fitview)){
            lefttab.addTab({
                id:"developtools",
                title:"开发工具箱",
                target:"#tools",
                onFirst:function(){
                    // databasegrid.loadRemote();
                }
            });
        }
        if(/(,|^)history(,|($))/.test(DataModelConfig.fitview)){
            lefttab.addTab({
                id:"operatehistory",
                title:"操作记录",
                target:"#history",
                onFirst:function(){
                    //databasegrid.loadRemote();
                }
            });
        }

        //右侧tab页面
        var intab=new Ladder.InTab("#intab",{container:".rightview"});
        intab.addTab({
            id:"basictab",
            title:"字段映射",
            target:"#basicinfo",
            current:true
        });
        intab.addTab({
            id:"eventstab",
            title:"事件脚本",
            target:"#eventinfo"
        });
        intab.addTab({
            id:"datatab",
            title:"交换数据",
            target:"#datainfo"
        });
        if(/(,|^)datagrid(,|($))/.test(DataModelConfig.fitview)){
            intab.addTab({
                id:"datagirdtab",
                title:"数据表格",
                target:"#datagird",
                onClick:function(){
                    var data=Ladder.toJSON($("#columns").val());
                    if(data) {
                        var count=0;
                        var fieldstr=[];
                        for(var i=0,len=data.length;i<len;i++){
                            var field=data[i];
                            if(field.isshow!=false){
                                fieldstr.push(field.as||field.fieldname);
                                count++;
                            }
                            if(count>5)break;
                        }

                        $("#queryfields").val(Ladder.toString(fieldstr, ",", ""));
                    }
                    if (!tempData.col_tablebox) {
                        tempData.col_tablebox = new Ladder.TableCombox("#queryfields",{
                            data:data,
                            multiSelect:true,
                            columns:[{title:"标题",fieldname:"title"},{title:"列名",fieldname:"fieldname"}],
                            queryform:[{title:"标题",formname:"title"},{title:"列名",formname:"fieldname"}],
                            chooser:"fieldname"
                        });
                    }else{
                        tempData.col_tablebox.setData(data);
                    }
                }
            });
        }
        if(/(,|^)genform(,|($))/.test(DataModelConfig.fitview)){
            intab.addTab({
                id: "genpagetab",
                title: "生成操作页面",
                target: "#genhtmlpage",
                onClick:function() {
                    $("#query",$("#genhtmlpage iframe")[0].contentDocument).val($("#name").val());
                    $("#save",$("#genhtmlpage iframe")[0].contentDocument).val($("#name").val());
                }
            });
        }
        if(/(,|^)api(,|($))/.test(DataModelConfig.fitview)){
            intab.addTab({
                title: "接口测试",
                target: "#apidebug",
            });
        }
        if(/(,|^)er(,|($))/.test(DataModelConfig.fitview)){
            intab.addTab({
                id:"er",
                title:"分属ER图",
                target:"#erview"
            });
        }
        if(/(,|^)sqlbug(,|($))/.test(DataModelConfig.fitview)){
            intab.addTab({
                id: "sqlbug",
                title: "sql日志",
                target: "#sqllog",
                onClick:function() {
                    var url = Ladder.Service.parseUrl("{webserver}service/SqlDebug.aspx?d=" +
                        Ladder.uuid() +
                        "&token=5645645645xzhy454545&length=8000&isClear=1");
                    $("#sqldebugiframe").attr("src",url );
                }
            });
        }

        var gridheight=($(window).height()-150)/2;
        //当前模版数据
        var cDataTemplateObject={
            id:null,
            bean:null,
            option:100,
            tableName: "DataModel",
            condition:"",
            showCount:0,
            direction:"DataModel"
        };
        var docs={
            sqldoc:null,
            tableNamedoc:null,
            sqldocHeight:80,
            tableNamedocHeight:80
        };
        var gensqldoc=CodeMirror.fromTextArea(document.getElementById("sqlname"), {
            lineNumbers: true,
            mode: "text/x-mariadb",
            indentWithTabs: true,
            smartIndent: true,
            matchBrackets : true,
            autofocus: true,
            tabSize:4,
            showCursorWhenSelecting:true,
            extraKeys: {"Alt-Down": "autocomplete"},
            hintOptions: {tables: {
                users: {name: null, score: null, birthDate: null},
                countries: {name: null, population: null, size: null}
            }}
        });
        gensqldoc.setSize('auto', '100');
        var outdoc=CodeMirror.fromTextArea(document.getElementById("outview"), {
            lineNumbers: true,
            mode: {name:"text/javascript"},
            indentWithTabs: true,
            smartIndent: true,
            matchBrackets : true,
            autofocus: true,
            tabSize:4,
            minHeight:100,
            extraKeys: {"Alt-Down": "autocomplete"},
            hintOptions: {tables: {
                users: {name: null, score: null, birthDate: null},
                countries: {name: null, population: null, size: null}
            }}
        });
        outdoc.setSize('auto', $(window).height()-265);
        //数据库表的datagrid
        var databasegrid=new Ladder.DataGrid("#databasegird",{
            queryUrl:URLS.QueryData,
            queryData:{tableName:"tables",psize:30,condition:{forms:DataModelConfig.tablescondition}},
            queryFormAction: 'auto|button',
            columnAlign: 'center',
            titleRowHeight: 30,
            multiSelect: false,
            fitView:"pager|queryform",
            layoutH:0,
            eventdblclick:function(){
                $("button.gen").trigger("click");
            }
        });
        databasegrid.addHeadButton("生成本表的模版","gen",function(){
            $("#gen").show();
            $("#dataTemplateform").hide();
            var nodeData=databasegrid.selectRow.data("rowData");
            gensqldoc.setValue(nodeData['table_schema']+"."+nodeData['table_name']);
            webajax(Ladder.ServerUrl + "/service/GetTableInfo.aspx", { tableName: nodeData['table_name'], schemaName: nodeData['table_schema'] }, function (result) {
                outdoc.setValue(writeTemplate(result.data));
            });
        });
        var columnstr="id,type,sort,title,name,tablename,updatetime";
        var dataTemplate=new Ladder.DataGrid("#grid",{
            queryUrl:URLS.QueryData,
            queryData:{tableName:"DataModel",condition:{columnString:columnstr},psize:30},
            queryFormAction: 'auto|button',
            columnAlign: 'center',
            titleRowHeight: 30,
            multiSelect: false,
            fitView:"pager|queryform,button",
            layoutH:0,
            words:15,
            onDblClick:rowDbClick
        });
        dataTemplate.setColumnConfig("type", { width: 40 });
        dataTemplate.setColumnConfig("sort", { width: 60 });
        dataTemplate.setColumnConfig("tablename",{words:10});
        dataTemplate.setColumnConfig("id", { isshow: false });
        dataTemplate.setColumnConfig("updatetime", {type:"date",format:"yyyy-MM-dd",width:80});
        dataTemplate.addHeadButton("高级查询", "insert", function () {
            layer.open({
                title: "高级查询",
                type: 1,
                area: ['720px', '450px'],//宽高
                content: dataTemplate.queryHtml()
            });
        });
        dataTemplate.loadRemote();
        var historydg=new Ladder.DataGrid("#history",{
            autoColumnModel:false,
            fitView:"button",
            // layoutH:0,
            onDblClick:function(){
                toTemplate({id:historydg.fetchgendata()});
            }
        });
        var backgrid=new Ladder.DataGrid("#backhistory",{
            queryUrl:URLS.QueryData,
            queryData:{tableName:"sqliteback",condition:{columnString:columnstr},psize:30},
            fitView:"queryform,pager",
            multiSelect:"multi",
            layoutH:0,
            onDblClick:function(tr,rowData){
                webajax(URLS.GetBean,{tableName:"sqliteback",condition:{id:rowData.id}},function(result){
                    if (result.statusCode == 200) {
                        $("#gen").hide();
                        $("#dataTemplateform").show();
                        cDataTemplateObject.id=rowData.id;
                        cDataTemplateObject.bean=result.data;
                        cDataTemplateObject.showCount++;
                        cDataTemplateObject.condition={name:rowData.name};
                        fetchTemplateInfo(-100);
                        cDataTemplateObject.direction="sqliteback";
                    }else{
                        layer.msg("获取备份数据失败");
                    }

                });
            }
        });
        backgrid.setColumnConfig("tablename",false);
        backgrid.addHeadButton("删除备份","deleteback",function(){
            var selected=backgrid.fetchSelectData();
            if(selected.length<1){
                layer.msg("请选择您要删除的备份记录");
                return;
            }
            var ids=Ladder.toString(selected,",","'");
            layer.confirm('请您确认是否备份记录', {
                btn: ['确认修改', '取消返回'], //按钮
                shade: false //不显示遮罩
            }, function () {
                webajax(URLS.SaveBean,{ tableName: "sqliteback", option: -1, condition: { "id:in": ids } },function(result) {
                    if (result.statusCode == 200) {
                        layer.msg("删除成功");
                        backgrid.loadRemote();
                    } else {
                        layer.msg("删除失败");
                    }
               });

            });

        });
        historydg.addHeadButton("清除缓存","clearbtn",function(){
            Ladder.setStore("TemplateHistory",[]);
            historydg.clear();
        });
        historydg.addColumn([
            {title:"id",fieldname:"id",gen:"uuid",isshow:false},
            {title:"类型",fieldname:"type"},
            {title:"分属",fieldname:"sort"},
            {title:"标题",fieldname:"title"},
            {title:"键表名",fieldname:"name"},
            {title:"访问时间",fieldname:"time"},
        ]);
        var fromDialog=new Ladder.FormDialog({
            tableName:"ColumnMapping",
            width:"600px",
            onRender:function(){
                var data=[];
                fromDialog.FieldModel.ColumnMapping.forEach(function(item){
                    data.push(item.fieldname);
                });
                var autocompelte1=new Ladder.AutoComplete("#propname",{
                    data:data
                });
                var autocompelte2=new Ladder.AutoComplete("#querypropname",{
                    data:data
                })
            }
        },"#EditColumnMapping");
        function fetchTemplateInfo(option){
            if(cDataTemplateObject.showCount==1){
                $("#datatab").trigger("click");
                docs.sqldoc=CodeMirror.fromTextArea(document.getElementById("sqlview"), {
                    lineNumbers: true,
                    mode: "text/x-mariadb",
                    indentWithTabs: true,
                    smartIndent: true,
                    matchBrackets : true,
                    autofocus: true,
                    tabSize:4,
                    extraKeys: {"Ctrl-/": "autocomplete"},
                    hintOptions: {tables: {
                        users: {name: null, score: null, birthDate: null},
                        countries: {name: null, population: null, size: null}
                    }}
                });
                $("#basictab").trigger("click");
                docs.sqldoc.setSize("100%", 115);
                docs.tableNamedoc=CodeMirror.fromTextArea(document.getElementById("tablename"), {
                    lineNumbers: true,
                    mode: "text/x-mariadb",
                    indentWithTabs: true,
                    smartIndent: true,
                    matchBrackets : true,
                    autofocus: true,
                    tabSize:4,
                    extraKeys: {"Ctrl-/": "autocomplete"},
                    hintOptions: {tables: {
                        users: {name: null, score: null, birthDate: null},
                        countries: {name: null, population: null, size: null}
                    }}
                });
                docs.tableNamedoc.setSize("100%", 80);
            }
            if(option==undefined || option==2){
                webajax(URLS.GetBean,cDataTemplateObject,function(result){
                    if(result.statusCode==200){
                        cDataTemplateObject.bean=result.data;
                        cDataTemplateObject.option=2;
                        if(!result.data.data)result.data.data="";
                        docs.sqldoc.setValue(result.data.data);
                        if(!result.data.tablename)result.data.tablename="";
                        docs.tableNamedoc.setValue(result.data.tablename);
                        delete result.data.data;
                        delete result.data.tablename;
                        Ladder.form.setFormValue("#dataTemplateform",result.data,"data-bind");
                        $(".repair[data-target='columns']").trigger("click");
                        $("#deleteTemplatebtn").show();
                    }
                    else{
                        layer.msg("获取模版数据错误");
                    }
                });
            }else{
                if(!cDataTemplateObject.bean.data)cDataTemplateObject.bean.data="";
                docs.sqldoc.setValue(cDataTemplateObject.bean.data);
                if(!cDataTemplateObject.bean.tablename)cDataTemplateObject.bean.tablename="";
                docs.tableNamedoc.setValue(cDataTemplateObject.bean.tablename);
                delete cDataTemplateObject.bean.data;
                delete cDataTemplateObject.bean.tablename;
                Ladder.form.setFormValue("#dataTemplateform",cDataTemplateObject.bean,"data-bind");
                $(".repair[data-target='columns']").trigger("click");
                $("#deleteTemplatebtn").show();
            }
        }
        //保存模版的修改
        $("#saveTemplatebtn").click(function(){
            cDataTemplateObject.bean=Ladder.form.fetchFormValue("#dataTemplateform","data-bind",false);
            cDataTemplateObject.bean.fromer=username;
            if(docs.sqldoc){
                cDataTemplateObject.bean.data=docs.sqldoc.getValue();
            }
            if(docs.tableNamedoc){
                cDataTemplateObject.bean.tablename=docs.tableNamedoc.getValue();
            }
            if(cDataTemplateObject.direction!="DataModel"){
                layer.confirm('请您确认是否还原式修改', {
                    btn: ['确认修改', '取消返回'], //按钮
                    shade: false //不显示遮罩
                }, function () {
                    cDataTemplateObject.option = 3;
                    toSave();
                });
            }else{
                toSave();
            }
            /**
             * 保存模版
             * @param selfuse 是否为方法自用，内部回溯调用
             */
            function toSave(selfuse){
                //非自用且是修改方法
                if(!selfuse && cDataTemplateObject.option==2){
                    var condition=$.extend({"updatetime:>":$("#updatetime").val()},cDataTemplateObject.condition);
                    webajax(URLS.GetCount,{tableName:cDataTemplateObject.tableName,condition:condition},function(result){
                        if(result.statusCode==200){
                            if(result.data==0)return toSave(true);
                            else{
                                layer.msg("当前模版已经修改，请重新获取修改",{icon:2});
                                return;
                            }
                        }
                        else{
                            layer.msg("也不知道乍回事，反正你就重新整吧");
                            return;
                        }
                    });
                    return;
                }
                if(!cDataTemplateObject.bean.analyzeitems)cDataTemplateObject.bean.analyzeitems="";
                webajax(URLS.SaveBean,cDataTemplateObject,function(result){
                    if(result.statusCode==200){
                        dataTemplate.loadRemote();
                        $("#updatetime").val(result.data.updatetime);
                        layer.msg("模版保存成功",{icon:1});
                        if(cDataTemplateObject.option==1){
                            cDataTemplateObject.option=2;
                            cDataTemplateObject.condition={id:result.data.id};
                        }
                    }
                    else layer.msg("模版保存失败",{icon:2});
                });
            }
            // webajax(URLS.BackDataModel, cDataTemplateObject);
        });
        //生成新的模版
        $("#genTemplatebtn").click(function(){
            var html=outdoc.getValue();
            var json="";
            if(html)json=eval("({"+html+"})");
            else json={newtemp:{}};
            for(var keyname in json){
                var templateObject=json[keyname];
                var formobject={name:keyname};
                for(var formname in templateObject){
                    var _type=Ladder.getType(templateObject[formname]);
                    if(/(Array)|(Object)/i.test(_type))
                        formobject[formname]=JSON.stringify(templateObject[formname]);
                    else  formobject[formname]=templateObject[formname];
                }
                formobject.fromer=username;
                formobject.updatetime=Ladder.dateFormat();
                formobject.data="";
                formobject.param="";
                $("#deleteTemplatebtn").hide();
                $("#outview").val("");
                $("#gen").hide();
                $("#dataTemplateform").show();
                cDataTemplateObject.bean=formobject;
                cDataTemplateObject.option=1;
                cDataTemplateObject.showCount++;
                fetchTemplateInfo(1);
                $("#deleteTemplatebtn").hide();
                break;
            }
        });
        //生成Bean模版
        $("#genBeanbtn").click(function(){
            var html=outdoc.getValue();
            var json="";
            if(html)json=eval("({"+html+"})");
            else return;
            for(var keyname in json){
                var templateObject=json[keyname];
                if(!templateObject["columns"])return;
                var outbean="";
                var outfun="";
                for(var i=0;i<templateObject["columns"].length;i++){
                    var field=templateObject["columns"][i];

                    outbean+="/// <summary>"+field["title"]+"</summary> \n public "+field["type"]+" "+field["fieldname"]+"{set;get;}\n";
    //                    outfun+="public "+field["type"]+" Get"
    //                            +field["fieldname"].toUpperCase().substr(0,1)
    //                            +field["fieldname"].substr(1,field["fieldname"].length-1)
    //                            +"(){\n"
    //                            +"\treturn this."+field["fieldname"]+";\n"
    //                            +"}\n"
    //                            +"public void Set"
    //                            +field["fieldname"].toUpperCase().substr(0,1)
    //                            +field["fieldname"].substr(1,field["fieldname"].length-1)
    //                            +"("+field["type"]+" "+field["fieldname"]+"){\n"
    //                            +"\tthis."+field["fieldname"]+"="+field["fieldname"]+";\n"
    //                            +"}\n"
    //
                }
                outdoc.setValue(outbean+outfun);

                break;
            }
        });
        //删除模版
        $("#deleteTemplatebtn").click(function(){
            if(cDataTemplateObject.option==1)return;
            layer.confirm('是否确定删除此模版', {icon: 3, title:'操作确认'}, function(index){
                layer.close(index);
                cDataTemplateObject.option=-1;
                cDataTemplateObject.bean=undefined;
                webajax(URLS.SaveBean,cDataTemplateObject,function(result){
                    if(result.statusCode==200){
                        dataTemplate.loadRemote();
                        layer.msg("模版删除成功",{icon:1});

                    }
                    else layer.msg("模版删除失败",{icon:2});
                });
            });
        });
        //增长代码区
        $(".increase").click(function(){
            var $this=$(this);
            var target=$this.attr("data-target");
            $("[data-bind='"+target+"']").height($("[data-bind='"+target+"']").height()+50);
            if(target=="data"){
                docs.sqldocHeight+=10;
                docs.sqldoc.setSize("100%",docs.sqldocHeight);
            }
        });
        //减短代码区
        $(".less").click(function(){
            var $this=$(this);
            var target=$this.attr("data-target");
            $("[data-bind='"+target+"']").height($("[data-bind='"+target+"']").height()-50);
            if(target=="data"){
                docs.sqldocHeight-=10;
                docs.sqldoc.setSize("100%",docs.sqldocHeight);
            }

        });
        $("#repaircolumnstext").click(function () {
            webajax(Ladder.ServerUrl+"/service/ToJson.aspx",{tableName:$("#columns").val()},function(ret){
                $("#columns").val(JSON.stringify(ret));
            });
        });

        //修复文本
        $(".repair").click(function(){
            var $this=$(this);
            var target=$this.attr("data-target");
            if(target)repairTemplateText(target);
        });
        //表格显示列模型
        $(".showgrid").click(function(){
            var $this=$(this);
            var target=$this.attr("data-target");
            if(/columns/.test(target)){
                layer.open({
                    type:1,
                    content:"<div class='js-showgrid' style='width: 1000px;height: 450px;margin: 0 auto'></div>",
                    title:"key:"+$("[data-bind='name']").val()+" type:"+$("[data-bind='type']").val()+" 列模型编辑器",
                    area: ['1024px', 'auto'],
                    btn:['选列文本',"关闭",'添加一行','批量修改','置行扩展','删除一行','上移一行','下移一行',"取值回置"],
                    fix:false,
                    shade:0.9,
                    yes:function(){
                        var $trs=cdg.datagrid.find("tbody tr");
                        cdg.handsort(2,1);
                        if($trs.length<1)return;
                        var text=[];
                        $trs.each(function(){
                            var $this=$(this);
                            if($this.find(".yui-datagrid-checkbox:checked").length<1)return;
                            var index=$this.find("[data-modelindex="+cdg.findModelIndex("index")+"]").text()*1;
                            if(index<0)index=text.length;
                            var fname=$this.find("[data-modelindex="+cdg.findModelIndex("fieldname")+"]").text();
                            var asstr=$this.find("[data-modelindex="+cdg.findModelIndex("as")+"]").text();
                            text.push((asstr?asstr:fname));
                        });
                        text=Ladder.toString(text,",");
                        $(".fieldText").val(text);
                    },
                    btn3:function(){
                        cdg.addRow(null,true,cdg.selectRow);
                    },
                    // btn4:function() {
                    //     cdg.setRowEdit(cdg.selectRow);
                    // },
                    //批量修改
                    btn4:function(){
                        var rawData = cdg.fetchSelectData(true);
                        if(!rawData||rawData.length<1)rawData=cdg.getGridData(1);
                        if(!rawData||rawData.length<1)return;
                        window.layerid = layer.open({
                            title:"批量修改",
                            type: 1,
                            content:$("#batchupdate"),
                            area:["300px","220px"]
                        });
                        $("#fieldname").val(Ladder.toString(rawData,",","","fieldname"));
                    },
                    //扩展编辑
                    btn5:function(){
                        if(!cdg.selectRow){
                            layer.msg("请选择行列数据");
                            return;
                        }
                        debugger;
                        var data = $.extend(cdg.getRowData(),cdg.getRowData(null,1));
                        if(data.settings)data.settings=decodeURIComponent(data.settings);
                        if(data.datasource)data.datasource=decodeURIComponent(data.datasource);
                        if(data.convert)data.convert=decodeURIComponent(data.convert);
                        fromDialog.open(data,false,function(){
                            var data = Ladder.Form.fetchFormValue("#EditColumnMapping","data-fieldname","data");
                            if(!data)return;
                            if(data.settings)data.settings=encodeURIComponent(data.settings);
                            if(data.datasource)data.datasource=encodeURIComponent(data.datasource);
                            if(data.convert)data.convert=encodeURIComponent(data.convert);
                            cdg.setCurrentRow(cdg.replaceRow(cdg.selectRow,data));
                            layer.msg("字段配置已经保存");
    //                        fromDialog.close();
                        },{
                            btn:['保存','取消返回','上一个字段','下一个字段'],
                            btn3:function() {
                                var prev=cdg.selectRow.prev();
                                if(prev.length<1)return;
                                cdg.setCurrentRow(prev);
                                var data = $.extend(cdg.getRowData(),cdg.getRowData(null,1));
                                if(data.settings)data.settings=decodeURIComponent(data.settings);
                                if(data.datasource)data.datasource=decodeURIComponent(data.datasource);
                                if(data.convert)data.convert=decodeURIComponent(data.convert);
                                fromDialog.setValue(data);
                            },
                            btn4:function() {
                                var next=cdg.selectRow.next();
                                if(next.length<1)return;
                                cdg.setCurrentRow(next);
                                var data = $.extend(cdg.getRowData(),cdg.getRowData(null,1));
                                if(data.settings)data.settings=decodeURIComponent(data.settings);
                                if(data.datasource)data.datasource=decodeURIComponent(data.datasource);
                                if(data.convert)data.convert=decodeURIComponent(data.convert);
                                fromDialog.setValue(data);
                            }
                        });
                        return;
                    },
                    // 删除一行
                    btn6:function(){
                        cdg.removeRow();
                    },
                    // 下移动
                    btn7:function(){
                        var $prev=cdg.selectRow.prev();
                        $prev.before(cdg.selectRow);
                    },
                    // 上移动
                    btn8:function(){
                        var $prev=cdg.selectRow.next();
                        $prev.after(cdg.selectRow);
                    },
                    //回值保存
                    btn9:function(){
                        tableToColumns();
                    }
                });
                window.cdg=new Ladder.DataGrid(".js-showgrid",{
                    autoColumnModel:false,
                    fitView:"queryform,button",
                    columnAlign:"center",
                    multiSelect:true,
                    onRowLeave:function(oldtr,newtr){
                        if(oldtr){
                            cdg.setDisplay($(oldtr));
                        }
                    },
                    onDblClick:function(tr){
                        cdg.setRowEdit(tr);
                    },
                    // thType:1,
                    bodyHeight:400
                });
                var index=0;
                var cols=[
    //                    { title:"序列",width:"40px",fieldname:"index",callback:function(){return ++index;}},
                    { title:"列名",fieldname:"fieldname"},
                    { title:"标题",fieldname:"title",width:"80px"},
                    { title:"类型",width:"65px",fieldname:"type",list:"string|date|datetime|number|int|file|text|bool"},
                    { title:"长度",width:"40px",fieldname:"length"},
                    { title:"排序",width:"60px",fieldname:"order",list:"|desc|asc|desc0|asc0|desc1|asc1|desc2|asc3|desc3|asc2|desc4|asc4"},
                    { title:"生成值",width:"65px",fieldname:"gen",list:"|autonum|id|uuid|date"},
                    { title:"默认值",fieldname:"dvalue",width:"60px"},
                    { title:"别名",fieldname:"as"},
                    { title:"分组名",fieldname:"groupname",width:"60px"},
                    { title:"显示顺序",fieldname:"isshow",width:"60px"},
                    { title:"编辑顺序",fieldname:"editable",width:"60px"}
                ];
                cdg.addColumn(cols);
                cdg.fillData($("[data-bind='columns']").val(),1);
                var $select=$("<select></select>").append("<option>文本字串</option>");

                $(cdg.settings.parentEL).find(".yui-dgqf ul").append("<li>显示文本字串:<input style='width:800px' class='fieldText'></li>");
                $(cdg.settings.parentEL).find(".yui-dgqf ul").find(".fieldText").on("input propertychange",function(){
                    var $input=$(this);
                    cdg.datagrid.find("tbody tr").each(function() {
                        var text = $(this).text();
                        if (text.indexOf($input.val()) > -1) {
                            $(this).show();
                        } else $(this).hide();

                    });
                });
                cdg.addHeadButton("按其他属性查询","propname",function(){
                    window.layerid = layer.open({
                        title:"按其他属性查询",
                        type: 1,
                        content:$("#queryprop"),
                        area:["300px","170px"]
                    });

                });
            }
        });
        //显示Json视图
        $(".showJson").click(function(){
            var $this=$(this);
            var target=$this.attr("data-target");
            var content = Ladder.form.getBindValue(target,"val");

            if(/(data)/.test(target)){
                if(docs.sqldoc){
                    content=docs.sqldoc.getValue();
                }
                // console.log(content);
                // content.replace(/[\r\n]/g,"")//去掉回车换行
            }
            else if(/(tablename)/.test(target)){
                if(docs.tableNamedoc){
                    content=docs.tableNamedoc.getValue();
                }
            }
            Ladder.setStore("tempData",Ladder.toJSON(content,true));
            layer.open({
                type: 2,
                title: target+"编辑查看视图",
                shadeClose: true,
                area: ['800px', '550px'],
                content:Ladder.BasicURL+"/page/JsonShow.html",
                fix:false,
                shade:0.9,
                btn:["保存回值","关闭取消"],
                yes:function(index,layero){
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var revalue=iframeWin.editor.getText();
                    Ladder.form.setBindValue(target,iframeWin.editor.getText(),true);
                    if(/(data)/.test(target) && docs.sqldoc){
                        content=docs.sqldoc.setValue(revalue);
                    }
                    else if(/(tablename)/.test(target) && docs.tableNamedoc){
                        docs.tableNamedoc.setValues(revalue);
                    }
                    layer.close(index);
                }
            });
        });
        //表单模版按钮
        $("#queryformbtn").click(function(){
            if(!Ladder.form.getBindValue("queryform")){
                Ladder.form.setBindValue("queryform",'{"list":[\n' +
                    '{"title":"姓名","formname":"full_name:like","inputType":"linetext"},\n' +
                    '{"title":"身份证","formname":"idcard:like","inputType":"linetext"}]}');
            }
        });
        //后续动作按钮
        $("#relationbtn").click(function(){
            if(!Ladder.form.getBindValue("events")){
                Ladder.form.setBindValue("events",'{\nupdateafter:[\n{"tableName":"employee","option":2,bean:"{full_name:\'@@full_name@@\'}",condition:"{member_id:\'@@id@@\'}"}]}');
            }
        });
        //扩展参数按钮
        $("#parambtn").click(function(){
            if(!Ladder.form.getBindValue("params")){
                Ladder.form.setBindValue("params",'[{"fieldname":"startdate","title":"开始日期","type":"string","length":20,"dvalue":"2016-11-12"}]');
            }
        });
        //手动生成字段映射
        $("#genColumnMapping").click(function() {
            if($("#type").val()=="program"){
                Ladder.CrossDomain=true;
                var url=$("#conn").val()||Ladder.ServerUrl+"/service/GetClassMappings.aspx";
                webajax(url,{className:docs.tableNamedoc.getValue()},function(result){
                    if(result.statusCode==200)
                        $("#columns").val(JSON.stringify(result.data));
                    else{
                        layer.msg("获取服务端方法失败");
                    }
                });
            } else {

                layer.msg('请确定您是附加字段还是覆盖字段',
                {
                    time: 0, //不自动关闭
                    icon: 8,
                    btn: ['原型字段', '联想字段', "返回"],
                    yes: function (index) {
                        layer.close(index);
                        requestMapping(0);
                    },
                    cancel: function (index) {
                        layer.close(index);
                        requestMapping(1);
                    },
                    btn3: function (index) {
                        layer.close(index);
                    }
                });
                function requestMapping(opt) {
                    webajax(Ladder.ServerUrl + "/service/GenColumnMappings.aspx", { mapping: opt, tableName: docs.tableNamedoc.getValue(), conn: $("#conn").val() }, function (result) {
                        if (result.statusCode == 200 && result.data) {
                            var oldcolumns = $("#columns").val();
                            if (oldcolumns) {
                                layer.msg('请确定您是附加字段还是覆盖字段', {
                                    time: 0, //不自动关闭
                                    icon: 8,
                                    btn: ['附加字段', '覆盖字段', "返回"],
                                    yes: function (index) {
                                        layer.close(index);
                                        var cls = Ladder.toJSON(oldcolumns);
                                        if (cls) {
                                            var map = {};
                                            var count = 0;
                                            cls.forEach(function (item) {
                                                map[item.fieldname] = true;
                                            });
                                            result.data.forEach(function (item) {
                                                if (!map.hasOwnProperty(item.fieldname)) {
                                                    cls.push(item);
                                                    count++;
                                                }
                                            });
                                            if (count > 0) {
                                                $("#columns").val(JSON.stringify(cls));
                                                layer.msg("添加了" + count + "个字段");
                                            } else {
                                                layer.msg("映射字段和当前字段相同");
                                            }
                                        }
                                    },
                                    cancel: function (index) {
                                        layer.close(index);
                                        $("#columns").val(JSON.stringify(result.data));
                                    },
                                    btn3: function (index) {
                                        layer.close(index);
                                    }
                                });
                            }
                            else {
                                $("#columns").val(JSON.stringify(result.data));
                            }
                        }
                    });
                }

            }
        });
        $("#genfieldmapping").click(function() {
            webajax(Ladder.ServerUrl + "/service/GenColumnMappings.aspx", { tableName: gensqldoc.getValue() }, function(result) {
                if (result.statusCode == 200 && result.data) {
                    outdoc.setValue(writeTemplate({ tablename: gensqldoc.getValue(), columns: result.data }));
                }
            });
        });
        $("#loadformdesign").click(function(){
            $("#formdesignpage")[0].contentWindow.init($("#columns").val());
        });
        $("#loaddatagrid").click(function() {
            var dg = new Ladder.DataGrid($("#datalist").empty(), {
                queryUrl: URLS.QueryData,
                queryData: { tableName: $("#name").val(), condition: { columns: $("#queryfields").val() } },
                layoutH: 0,
                fitView: "pager,caption,settings"
            });
            dg.loadRemote();
        });
        //数据库表操作选项
        $("#columnsbtn").dblclick(function(){
            layer.open({
                type:1,
                content:$("#createTableForm"),
                title:"数据库表操作选项",
                area:["300px","100px"],
                shadeClose:true
            });
        });
        //创建表
        $("#creaTetableBtn").click(function(){
            webajax(Ladder.ServerUrl+"/service/CreateTable.aspx",{tableName:Ladder.form.getBindValue("name")},function(result){
                if(result.statusCode==200){
                    layer.closeAll();
                    layer.msg("创建表成功");
                }else{
                    layer.closeAll();
                    layer.msg("创建表失败["+result.message+"]");
                }
            });
        });
        //批量修改按钮2
        $("#batchupdatebtn2").click(function(){
            batchupdate();
        });
        //批量修改按钮
        $("#batchupdatebtn").click(function(){
            batchupdate(true);
        });
        //按照属性查询
        $("#querypropvalue").keyup(function(e){
            if (e.keyCode == 13) {
                $("#querypropbtn").trigger("click");
            }
        })
        //按照属性查询
        $("#querypropbtn").click(function(){
              var p = $("#querypropname").val();
              var v = $("#querypropvalue").val();
              if(!p){
                  cdg.datagrid.find("tbody tr").show();
                  return;
              }
              cdg.datagrid.find("tbody tr").each(function() {
                 var rawData = cdg.getRowData(this,0);
                 var htmlData = cdg.getRowData(this,1);
                 if(v.length<1&&(rawData.hasOwnProperty(p)||htmlData.hasOwnProperty(p))){
                     $(this).show();
                     return;
                 }
                 if(v.length>0&&rawData[p]&&rawData[p].indexOf(v)>-1){
                     $(this).show();
                     return;
                 }
                  if(v.length>0&&htmlData[p]&&htmlData[p].indexOf(v)>-1){
                      $(this).show();
                      return;
                  }
                  $(this).hide();
              });
         });
        //添加事件
        $("#addEventbtn").click(function(){
            eventsDialog.open({},false,function(data){
               var old = Ladder.toJSON($("#events").val());
               if(!old) old={};
               var eventname=data.event;
               delete data.event;
               if(old.hasOwnProperty(eventname)){
                   old[eventname].push(data);
               }else{
                   old[eventname]=[data];
               }
               $("#events").val(JSON.stringify(old));
               eventsDialog.close();
            });
        });
        //克隆模版
        $("#copyTemplatebtn").click(function() {
            layer.open({
                type: 1,
                title:"请输入另存的键名",
                fix: false,
                shade: 0.9,
                content: "<div style='margin:4px;text-align: center;'>模版键名:<input id='saveasname'></div>",
                btn: ["保存模版", "取消返回"],
                yes:function(index) {
                    var name = $("#saveasname").val();
                    if (!name) {
                        layer.msg("对不起，请输入模版的键名");
                        return;
                    }
                    var bean = Ladder.form.fetchFormValue("#dataTemplateform", "data-bind", false);
                    bean.fromer = username;
                    bean.name = name;
                    if (docs.sqldoc) {
                        bean.data = docs.sqldoc.getValue();
                    }
                    if (docs.tableNamedoc) {
                        bean.tablename = docs.tableNamedoc.getValue();
                    }
                    webajax(URLS.SaveBean, {tableName:"DataModel",option:1,bean:bean}, function (result) {
                        if (result.statusCode == 200) {
                            dataTemplate.loadRemote();
                            layer.msg("模版保存成功", { icon: 1 });

                        }
                        else layer.msg("模版保存失败", { icon: 2 });
                    });
                    layer.close(index);
                }

            });


        });
        // 发布模版
        $("#publishTemplatebtn").click(function() {
            layer.open({
                type: 1,
                title: "发布模版",
                content: $("#pulishView"),
                btn: ["确认发布", "取消返回"],
                yes: function(layerno) {
                    var tableName = $("#name").val();
                    var conn = $("#connname").val();
                    var table = $("#table").val();
                    webajax(URLS.SyncDataModel,{ conn: conn, tableName: tableName, table: table },function(result) {
                        if (result.statusCode == 200) {
                            layer.msg("发布成功");
                            setTimeout(function() {
                                layer.close(layerno);
                            },1500);
                        } else {
                            layer.msg("发布失败,请重试！！！");
                        }
                    });
                }
            });
        });
        //导出模版
        $("#exportTemplatebtn").click(function(){
            layer.open({
                type:1,
                content:$("#exportView"),
                area:["800px","600px"],
                title:"模版导出"
            });
            $("#exportView select").off().change(function(){exprotText()});
            setTimeout(function(){
                exprotText()
            },500);
        });
        //导出的编辑器
        var outcodeEditer=CodeMirror.fromTextArea(document.getElementById("outTextView"), {
            mode: "xml",
            lineNumbers: true,
            smartIndent:true
        });
        outcodeEditer.setSize("auto",510);
        //导出文本
        function exprotText(){
            var type =  $("#exportView select").val();
            var bean=Ladder.form.fetchFormValue("#dataTemplateform","data-bind",false);
            bean.fromer=username;
            if(docs.sqldoc){
                bean.data=docs.sqldoc.getValue();
            }
            if(docs.tableNamedoc){
                bean.tablename=docs.tableNamedoc.getValue();
            }
            bean.columns=Ladder.toJSON(bean.columns);
            bean.queryform=Ladder.toJSON(bean.queryform);
            switch (type){
                case "json":
                    outcodeEditer.setOption("mode",{name:"text/javascript",json:true});
                    outcodeEditer.setValue(JSON.stringify(bean,null, 2));
                    break;
                case "xml":
                    var xml = Ladder.tpl("#outxml",bean);
                    outcodeEditer.setOption("mode","xml");
                    outcodeEditer.setValue(xml.replace(/^\s*/g,"")
                        .replace(/>\s*</g,"><")
                        .replace(/>/g,">\n")
                        .replace(/>\s*<\/column>/g,"></column>")
                        .replace(/<column\s/g,"\t<column ")
                    );
                    break;
            }
        }
        var templateHtml="";
        //批量更新
        function batchupdate(isupdate){
            var fieldnames=$("#fieldname").val();
            var propname = $("#propname").val();
            var value=$("#propvalue").val();
            if(!propname)return;
            fieldnames=","+fieldnames+",";
            var $trs=cdg.datagrid.find("tbody tr");
            $trs.each(function(){
                var $this = $(this);
                var htmlRowData = cdg.getRowData($this,1);
                for (var p in htmlRowData){
                    if((""+htmlRowData[p]).length<1){
                        delete htmlRowData[p];
                    }
                }
                if(fieldnames.indexOf(","+htmlRowData.fieldname+",")>-1){
                    var rowdata=cdg.getRowData($this);
                    if(value.length>0){
                        htmlRowData[propname]=value;
                    }else{
                        delete htmlRowData[propname];
                        delete rowdata[propname];
                    }

                    cdg.replaceRow($this,$.extend(rowdata,htmlRowData));
                }
            });
            layer.msg("保存成功");
            layer.close(layerid);
            if(isupdate){
                tableToColumns(false);
            }
        }
        //从列模型表格保存到Columns中
        function tableToColumns(isclose){
            var $trs=cdg.datagrid.find("tbody tr");
            if($trs.length<1){
                Ladder.form.setBindValue("columns","");
                layer.closeAll();
                return;
            }
            setdispaly();
    //                        cdg.handsort(2,1);
            var temp=[];
            cdg.datagrid.find("tbody tr").each(function(){
                var re_t={};
                var $tr=$(this);
                $tr.find("td").each(function(){
                    var $this=$(this);
                    var mi=$this.attr("data-modelindex");
                    if(!/^\d*$/.test(mi))return;
                    var cm=cdg.getColumnModel(mi);
                    var value=$this.text();
                    if(value.length<1)return;
                    re_t[cm.fieldname]=handleValue(value);
                    function handleValue(val){
                        if(/false/.test(val))return false;
                        if(/true/.test(val))return true;
                        if(/(^\d+$)|(^\d+\.\d+$)/.test(val)) return val*1;
                        return val;
                    }
                });
                var raw=$tr.data("rowData");
                temp.push($.extend(raw,re_t));
            });
            Ladder.form.setBindValue("columns",JSON.stringify(temp));
            $("#saveTemplatebtn").trigger("click");
            if(isclose==undefined||isclose)layer.closeAll();
            function setdispaly() {
                cdg.datagrid.find("tbody tr").each(function() {
                    cdg.setDisplay($(this));
                });
            }
        }
        //修复模板文本
        function repairTemplateText(name){
            if(name==undefined || name.indexOf("columns")>-1){
                var $columns=$("[data-bind='columns']");
                if($columns.val()){
                    templateHtml=$columns.val().replace(/},\s*/g,"},");
                    var i=repairText("},",0,"\n");
                    while(i>0){
                        i= repairText("},",i,"\n");
                    }
                    $columns.val(templateHtml);
                }
            }
            if(name==undefined || name.indexOf("queryform")>-1){
                var $queryform=$("[data-bind='queryform']");
                if($queryform.val()){
                    templateHtml=$queryform.val().replace(/\s*/g,"");
                    var i=repairText('list":[',0,"\n\t");
                    while(i>0){
                        i= repairText("},",i,"\n\t");
                    }

                    $queryform.val(templateHtml);
                }
            }
        }
        function writeTemplate(data){
            templateHtml="newtemp:"+JSON.stringify(data);
            repairText("{");
            repairText(",");
            var i=repairText("},",0,"\n\t\t");
            while(i>0){
                i= repairText("},",i,"\n\t\t");
            }
            repairText("}]",0,"\n");

            return templateHtml;
        }
        //修复json文本
        function repairText(searchtext,startIndex,content,text){
            var isupdate=false;
            if(text==undefined){
                isupdate=true;
                text=templateHtml;
            }
            if(content==undefined)content="\n\t";
            var index=text.indexOf(searchtext,startIndex);
            if(index<0){
                if(isupdate) return -1;
                else return text;
            }
            index=index+searchtext.length;
            var lefttext=text.substring(0,index);
            var righttext=text.substring(index);
            if(isupdate){
                templateHtml=lefttext+content+righttext;
                return index;
            }
            return lefttext+content+righttext;
        }
        //双击模版行
        function rowDbClick(tr,rowData){
            toTemplate({id:dataTemplate.fetchgendata()});
            if(historydg.getRowCount()&&historydg.getRowData(0).name==rowData.name)return;
            var history=rowData;
            history.time=Ladder.dateFormat();
            historydg.addRow(history);
            historyData.splice(0,0,history);
            Ladder.setStore("TemplateHistory",historyData);
            $("#sort",$("#erview iframe")[0].contentDocument).val(rowData.sort);
        }
        window.toTemplate=function(condition){
            intab.switchTo(0);
            cDataTemplateObject.showCount++;
            cDataTemplateObject.condition=condition;
            cDataTemplateObject.option=-100;
            cDataTemplateObject.bean=undefined;
            cDataTemplateObject.direction="DataModel";
            $("#gen").hide();
            $("#dataTemplateform").show();
            fetchTemplateInfo();
            setTimeout(function(){
                $("#datalist").empty();
            },1000);
        }
        var autocomplete=new Ladder.AutoComplete("#sort",{
            queryUrl:URLS.GetData,
            queryData:{tableName:"DataModel",columns:"sort"},
            form:'sort',
            // repeatRequest:false
        });
        var historyData= Ladder.getStore("TemplateHistory");
        if(!historyData)historyData=[];
        historydg.fillData(historyData,1);
        //事件添加的弹窗
        var eventsDialog=new Ladder.FormDialog({
            tableName:"Events",
            width:"600px",
            formFormat:"data",
            onRender:function(){
                // var data=[];
                // fromDialog.FieldModel.ColumnMapping.forEach(function(item){
                //     data.push(item.fieldname);
                // });
                // var autocompelte1=new Ladder.AutoComplete("#propname",{
                //     data:data
                // });
                // var autocompelte2=new Ladder.AutoComplete("#querypropname",{
                //     data:data
                // })
            }
        });
    };
	if(typeof define === "function" && define.amd){
		require.config({baseUrl:GetRequireUrl()});
		require(['ladder'],__functionForDataModel);
	}
	else __functionForDataModel();
})();





